package com.ruoyi.oss.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.oss.service.IOssService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * OSS文件管理控制器
 * 
 * @author ruoyi
 * @date 2025-01-20
 */
@RestController
@RequestMapping("/oss")
public class OssController extends BaseController {
    
    private static final Logger logger = LoggerFactory.getLogger(OssController.class);
    
    @Autowired
    @Qualifier("ossServiceImpl")
    private IOssService ossService;
    
    /**
     * 上传文件到OSS
     */
    @Anonymous
    @Log(title = "文件上传", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return error("请选择要上传的文件");
            }
            
            // 验证文件大小（限制为10MB）
            if (file.getSize() > 10 * 1024 * 1024) {
                return error("文件大小不能超过10MB");
            }
            
            // 上传到OSS
            String fileUrl = ossService.uploadFile(file);
            
            Map<String, Object> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("message", "上传成功");
            
            return success(result);
            
        } catch (Exception e) {
            logger.error("文件上传失败", e);
            return error("文件上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 上传文件到OSS（指定路径）
     */
    @Anonymous
    @Log(title = "文件上传", businessType = BusinessType.INSERT)
    @PostMapping("/upload-path")
    public AjaxResult uploadFileWithPath(@RequestParam("file") MultipartFile file, 
                                       @RequestParam("path") String path) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return error("请选择要上传的文件");
            }
            
            // 验证文件大小（限制为10MB）
            if (file.getSize() > 10 * 1024 * 1024) {
                return error("文件大小不能超过10MB");
            }
            
            // 验证路径
            if (path == null || path.trim().isEmpty()) {
                return error("上传路径不能为空");
            }
            
            // 确保路径以/结尾
            if (!path.endsWith("/")) {
                path = path + "/";
            }
            
            // 上传到OSS
            String fileUrl = ossService.uploadFile(file, path);
            
            Map<String, Object> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("message", "上传成功");
            
            return success(result);
            
        } catch (Exception e) {
            logger.error("文件上传失败", e);
            return error("文件上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 上传头像到OSS
     */
    @Anonymous
    @Log(title = "头像上传", businessType = BusinessType.INSERT)
    @PostMapping("/upload-avatar")
    public AjaxResult uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return error("请选择要上传的文件");
            }
            
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return error("只能上传图片文件");
            }
            
            // 验证文件大小（限制为5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return error("文件大小不能超过5MB");
            }
            
            // 上传到OSS，指定头像专用路径
            String imageUrl = ossService.uploadFile(file, "avatars/");
            
            Map<String, Object> result = new HashMap<>();
            result.put("url", imageUrl);
            result.put("message", "上传成功");
            
            return success(result);
            
        } catch (Exception e) {
            logger.error("头像上传失败", e);
            return error("头像上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除OSS文件
     */
    @PreAuthorize("@ss.hasPermi('oss:file:delete')")
    @Log(title = "删除OSS文件", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete")
    public AjaxResult deleteFile(@RequestParam("url") String url) {
        try {
            if (url == null || url.trim().isEmpty()) {
                return error("文件URL不能为空");
            }
            
            boolean success = ossService.deleteFile(url);
            if (success) {
                return success("删除成功");
            } else {
                return error("删除失败");
            }
        } catch (Exception e) {
            logger.error("删除OSS文件失败", e);
            return error("删除失败: " + e.getMessage());
        }
    }
} 